package files

import (
	"context"
	v1 "devops-super/api/file/v1"
	"devops-super/internal/consts"
	"devops-super/internal/service"
	"devops-super/utility/upload"
	"devops-super/utility/util/fileUtil"
	"errors"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/tiger1103/gfast/v3/library/liberr"
	"os"
)

func (*sFile) CommonBase64Upload(ctx context.Context, base64Data string) (url string, err error) {
	err = g.Try(ctx, func(ctx context.Context) {
		v, _ := g.Cfg().Get(ctx, "upload.default")
		upres, err := service.File().UploadBase64(ctx, base64Data, v.Int())
		if err != nil {
			return
		}
		url = upres.FullPath
		return
	})
	return
}

func (*sFile) CommonUpload(ctx context.Context, req *v1.FileCommonUploadReq) (res *v1.FileCommonUploadRes, err error) {
	res = new(v1.FileCommonUploadRes)
	err = g.Try(ctx, func(ctx context.Context) {
		if req.File == nil {
			err = errors.New("no file")
			liberr.ErrIsNil(ctx, err, "no file")
			return
		}
		tmpDir := "/tmp/"
		filename1, err := req.File.Save(tmpDir)
		tmpFileFullPath := tmpDir + filename1
		resultMd5 := fileUtil.CountFileMd5(ctx, tmpFileFullPath)

		if err != nil {
			return
		} else {
			defer func(name string) {
				_ = os.Remove(name)
			}(tmpFileFullPath)
		}
		v, _ := g.Cfg().Get(ctx, "upload.default")
		upres, err := service.File().UploadFile(ctx, req.File, consts.CheckFileTypeFile, v.Int())
		if err != nil {
			return
		}

		res.Url = upres.FullPath
		res.FileMd5 = resultMd5
		return
	})
	return
}

// UploadFiles 上传多文件
func (s *sFile) UploadFiles(ctx context.Context, files []*ghttp.UploadFile, checkFileType string, source int) (result v1.UploadMultipleRes, err error) {
	for _, item := range files {
		f, e := s.UploadFile(ctx, item, checkFileType, source)
		if e != nil {
			return
		}
		result = append(result, &f)
	}
	return
}

// UploadFile 上传单文件
func (s *sFile) UploadFile(ctx context.Context, file *ghttp.UploadFile, checkFileType string, source int) (result v1.UploadResponse, err error) {

	uploader := upload.GetUploader(upload.UploaderType(source))
	if uploader == nil {
		err = errors.New("没有找到上传适配器")
		return
	}
	return uploader.Upload(ctx, file)
}

func (s *sFile) UploadBase64(ctx context.Context, base64Str string, source int) (result v1.UploadResponse, err error) {
	uploader := upload.GetUploader(upload.UploaderType(source))
	if uploader == nil {
		err = errors.New("没有找到上传适配器")
		return
	}
	return uploader.UploadBase64(ctx, base64Str)
}
